package com.huabo.contract.service.impl;

import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.PageInfo;
import com.huabo.contract.config.DateBaseConfig;
import com.huabo.contract.oracle.entity.*;
import com.huabo.contract.oracle.mapper.TblContractLendMapper;
import com.huabo.contract.oracle.mapper.TblCyhwUnitMapper;
import com.huabo.contract.service.TblCirculationService;
import com.huabo.contract.service.TblContractLendService;
import com.huabo.contract.service.TblMyTaskService;
import com.huabo.contract.service.TblProcessAnalusisUserService;
import com.huabo.contract.service.TblProcessAnalysisService;
import com.huabo.contract.service.TblStaffService;
import com.huabo.contract.util.HttpClient;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class TblContractLendServiceImpl implements TblContractLendService {

    @Resource
    private TblCyhwUnitMapper tblCyhwUnitMapper;

    @Resource
    private TblContractLendMapper tblContractLendMapper;

    @Resource
    private TblProcessAnalysisService tblProcessAnalysisService;
    
    @Resource
    private TblProcessAnalusisUserService tblProcessAnalusisUserService;
    
    @Resource
    private TblCirculationService tblCirculationService;

    @Resource
    private TblStaffService tblStaffService;
    
    @Resource
    private TblMyTaskService tblMyTaskService;
    
    @Override
    public Map<String, Object> saveTblContractLead(String contractId,String lenddate,String returndate, String token, String staffId, TblContractLend lend) throws Exception {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            TblCyhwUnit tbcontract = null;
            String result = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            lend.setLenddate(sdf.parse(lenddate));//借阅日期
            lend.setReturndate(sdf.parse(returndate));//归还日期
            try {
                TblStaffUtil user = DealUserToken.parseUserToken(token);
                if (user == null) {
                    resultMap.put("code", "0");
                    resultMap.put("msg", "用户已失效！");
                    return resultMap;
                }
                //tbcontract=tblCyhwUnitMapper.findContractById(Integer.parseInt(contractId));
                if (null != lend.getLendid()) {
                    this.tblContractLendMapper.updateTblContractLead(lend);
                } else {
                    lend.setUserid(user.getStaffid());
                    lend.setLendstatus(1);//1.借阅审批中
                    lend.setContractid(new BigDecimal(contractId));
                    this.tblContractLendMapper.saveTblContractLead(lend);
                }
                this.ContractLendApproval(user,lend.getLendid());
                resultMap.put("code", "1");
                resultMap.put("msg", "成功！");

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            TblCyhwUnit tbcontract = null;
            String result = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            lend.setLenddate(sdf.parse(lenddate));//借阅日期
            lend.setReturndate(sdf.parse(returndate));//归还日期
            try {
                TblStaffUtil user = DealUserToken.parseUserToken(token);
                if (user == null) {
                    resultMap.put("code", "0");
                    resultMap.put("msg", "用户已失效！");
                    return resultMap;
                }
                //tbcontract=tblCyhwUnitMapper.findContractById(Integer.parseInt(contractId));
                if (null != lend.getLendid()) {
                    this.tblContractLendMapper.updateTblContractLead(lend);
                } else {
                    lend.setUserid(user.getStaffid());
                    lend.setLendstatus(1);//1.借阅审批中
                    lend.setContractid(new BigDecimal(contractId));
                    this.tblContractLendMapper.saveTblContractLead(lend);
                }
                resultMap.put("code", "1");
                resultMap.put("msg", "成功！");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        }
    }

    private void ContractLendApproval(TblStaffUtil user, BigDecimal lendid) throws Exception {
    	List<TblProcessAnalysis> list = tblProcessAnalysisService.getByModuel(TblContractLend.htjyProcessName);//合同借阅暂时固定流程
		//将审批流程过程中的角色、节点等信息保存
		HashMap<String, Object> fields = new HashMap<String, Object>();
		TblProcessAnalusisUser analysisUser = null;
		if(list!=null && list.size()>0){
			for (TblProcessAnalysis tblAnalysis : list) {
				analysisUser = tblProcessAnalusisUserService.findOnd(tblAnalysis.getAnalid().toString(), lendid.toString());
				if(analysisUser==null){
					analysisUser=new TblProcessAnalusisUser();
					analysisUser.setAnalid(tblAnalysis.getAnalid().toString());
					analysisUser.setFromid(lendid.toString());
					analysisUser.setSpdate(new Date());
					if(tblAnalysis.getUserid()!=null){
						analysisUser.setStaffid(user.getRealname());
					}else{
						analysisUser.setStaffid(tblAnalysis.getRolename());
					}
					tblProcessAnalusisUserService.insertSetting(analysisUser);
				}
				//合同订立流程参数
				//提交人参数
				if(tblAnalysis.getUserid()!=null&&tblAnalysis.getUserid().equals("tcuserid")) {
					fields.put("tcuserid", user.getStaffid().toString());
					analysisUser.setStaffid(tblAnalysis.getRolename());
					System.out.println("tcuserid:"+user.getStaffid());
				}
			}
		}
		
		net.sf.json.JSONObject jsonObject=net.sf.json.JSONObject.fromObject(fields);
		Map<String, Object> map = HttpClient.startProcessAll(TblContractLend.htjyProcessName,jsonObject.toString());
		String object = (String) map.get("result");
		String processInstanceId = (String) map.get("processInstanceId");
		String processDefinitionKey = (String) map.get("processDefinitionKey");
		TblCirculation cir = tblCirculationService.saveTblCirculationnew(TblContractLend.HTJY_TYPE,lendid.toString(),TblContractLend.HTJY_TYPE,TblContractLend.HTJY_URL+lendid,user.getStaffid(),processInstanceId,processDefinitionKey,lendid.toString());
		if(object!=null && object.equals("true")){
			this.tblContractLendMapper.updateLendStatus(lendid, TblContractLend.STATE_SP);//修改借阅状态
			List<TblMyTask> tasks = HttpClient.findByTask("", user.getStaffid().toString(), 1, 500000);
			TblProcessAnalysis analysis = null;
			TblProcessAnalysis analysis1 = null;
			TblProcessAnalusisUser analysisUser1 = null;
			Integer number=1;
			TblStaff bmfzr = null;
			if(tasks!=null && tasks.size()>0){
				for (TblMyTask task : tasks) {
					//各个审批节点任务
					if(task.getProcessInstanceId().equals(processInstanceId)){
						Map<String, Object> map1 = HttpClient.handleProcessJson(user.getStaffid().toString(),"通过",task.getTaskId());
						String result = (String) map1.get("result");
						if(result!=null && "true".equals(result)){
							String blande="";
							String nextapprover = HttpClient.nextapprover(cir.getBusinesskey());
							analysis = tblProcessAnalysisService.findOndBytakdidstart(blande,TblContractLend.htjyProcessName);
							number=1;
							String usertaskid = analysis.getUsertaskid();
							Integer num = Integer.parseInt(usertaskid.substring(usertaskid.length()-1,usertaskid.length()))+number;
							blande = usertaskid.substring(0,usertaskid.length()-1)+num;
							analysis1 = tblProcessAnalysisService.findOndBytakdidstart(blande,TblContractLend.htjyProcessName);
							analysisUser1 = tblProcessAnalusisUserService.findOnd(analysis1.getAnalid().toString(), lendid.toString());
							task.setFromid(lendid.toString());
							task.setApprover(user.getRealname());
							task.setUsrid(user.getStaffid().toString());
							task.setExamination("提交审批");
							task.setProcessName(TblContractLend.htjyProcessName);
							if(user.getTrole() !=null && user.getTrole().getRname() !=null){
								task.setApprovalrole(user.getTrole().getRname());
							}
							task.setApprovaldate(new Date());
							task.setResult("通过");
							task.setCirid(cir.getCyid().toString());
							if(nextapprover.contains("bmfzr")) {
								bmfzr = tblStaffService.findByJobName("部门负责人", user.getCurrentOrg().getOrgid().toString());
								task.setHandle(bmfzr.getRealname());
							}else if(nextapprover.contains("fgld")) {
								//分管领导参数
								TblStaff fgld = tblStaffService.findByStaffManOrgs(user.getCurrentOrg().getOrgid().toString());
								task.setHandle(fgld.getRealname());
							}else {
								task.setHandle(nextapprover);
							}
							task.setAnalid(analysisUser1.getAnalid().toString());
							tblMyTaskService.updateSetting(task);
						}
					}
				}
				
			}
			System.out.println("发送审批成功");
		}else{
			System.out.println("发送审批失败");
		}
	}

	@Override
    public Map<String, Object> findByContractId(Integer pageNumber, Integer pageSize, String contractId, String token, String staffId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            Map<String, Object> dataMap = new HashMap<String, Object>(0);
            try {
                TblStaffUtil user = DealUserToken.parseUserToken(token);
                if (user == null) {
                    resultMap.put("code", "0");
                    resultMap.put("msg", "用户已失效！");
                    return resultMap;
                }
                //TblCyhwUnit tbcontract= tblCyhwUnitMapper.findContractById(Integer.parseInt(contractId));
                TblContractLend tblContractLead = new TblContractLend();
                tblContractLead.setContractid(new BigDecimal(contractId));
                PageInfo<TblContractLend> pageInfo = new PageInfo<TblContractLend>();
                pageInfo.setCondition(tblContractLead);
                pageInfo.setCurrentPage(pageNumber);
                pageInfo.setPageSize(pageSize);
                pageInfo.setTlist(tblContractLendMapper.findByContractId(pageInfo));
                pageInfo.setTotalRecord(tblContractLendMapper.findCountByContractId(pageInfo));
                dataMap.put("pageInfo", pageInfo);
                dataMap.put("currentUser", user);
                resultMap.put("code", "1");
                resultMap.put("msg", "成功！");
                resultMap.put("data", dataMap);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            Map<String, Object> dataMap = new HashMap<String, Object>(0);
            try {
                TblStaffUtil user = DealUserToken.parseUserToken(token);
                if (user == null) {
                    resultMap.put("code", "0");
                    resultMap.put("msg", "用户已失效！");
                    return resultMap;
                }
                //TblCyhwUnit tbcontract= tblCyhwUnitMapper.findContractById(Integer.parseInt(contractId));
                TblContractLend tblContractLead = new TblContractLend();
                tblContractLead.setContractid(new BigDecimal(contractId));
                PageInfo<TblContractLend> pageInfo = new PageInfo<TblContractLend>();
                pageInfo.setCondition(tblContractLead);
                pageInfo.setCurrentPage(pageNumber);
                pageInfo.setPageSize(pageSize);
                pageInfo.setTlist(tblContractLendMapper.findByContractId(pageInfo));
                pageInfo.setTotalRecord(tblContractLendMapper.findCountByContractId(pageInfo));
                dataMap.put("pageInfo", pageInfo);
                dataMap.put("currentUser", user);
                resultMap.put("code", "1");
                resultMap.put("msg", "成功！");
                resultMap.put("data", dataMap);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        }
    }

    @Override
    public TblContractLend findById(String lendid) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return tblContractLendMapper.findById(lendid);
        } else {
            return tblContractLendMapper.findById(lendid);
        }
    }

	@Override
	public void saveTblContractLeadEntity(TblContractLend lend) {
		 this.tblContractLendMapper.updateTblContractLead(lend);
	}

}
